#!/usr/bin/python

from optparse import OptionParser
import os, string, subprocess, sys, os.path

file_dir = os.path.dirname(os.path.abspath(__file__))
if file_dir[-9:] == "bin/linux":
   overfeat_dir = os.path.join(file_dir, "../..")
elif file_dir[-3:] == "src":
   overfeat_dir = os.path.join(file_dir, "..")
else:
   overfeat_dir = file_dir
try:
   path_env = os.environ['OVERFEAT_NETDIR']
   if path_env != "":
      overfeat_dir = path_env
except KeyError:
   pass
default_data_dir = os.path.join(overfeat_dir, "data/default")

parser = OptionParser()
parser.description = "See README.md for more details"
parser.add_option("-d", "--data_dir", dest="data_dir", action="store", default=default_data_dir, help="Path to the folder containing the model data")
parser.add_option("-i", "--input_dir", dest="input_dir", action="store", help="Input directory")
parser.add_option("-o", "--output_dir", dest="output_dir", action="store", help="output directory")
parser.add_option("-l", "--large_net", dest="large_net", action="store_true", default=False, help="Use larger but slower network")
(options, args) = parser.parse_args()

if (options.input_dir == None) or (options.output_dir == None):
   parser.print_help()
   sys.exit(0)

net_idx = 1 if options.large_net else 0

if not os.path.exists(options.data_dir):
   if options.data_dir != default_data_dir:
      print >> sys.stderr, "Specified path to data (%s) does not exist"%(options.data_dir)
   else:
      print >> sys.stderr, "Cannot find default path to the model data files (%s).\n Please manually specify it with option -d"%(options.data_dir)
   sys.exit(0)
weight_file = options.data_dir
if not os.path.exists(os.path.join(weight_file, "net_weight_%d"%(net_idx))):
   print >> sys.stderr, "File %s does not exists. Please check your path, or use option -d"%(weight_file)

if not os.path.exists(options.input_dir):
    print >> sys.stderr, "Input directory doesn't exist"
    sys.exit(0)
if not os.path.exists(options.output_dir):
    os.mkdir(options.output_dir)

toprocess = os.listdir(options.input_dir)
toprocess_input = [os.path.join(options.input_dir, x) for x in toprocess]

p = subprocess.Popen("convert %s ppm:- | %s/overfeat %s -d %s -p -f"%(string.join(toprocess_input, " "),
                                                                      file_dir,
                                                                      "-l" if options.large_net else "",
                                                                      weight_file),
                     stderr=sys.stderr, shell=True, stdout = subprocess.PIPE)
          
linetype = 0
i = 0
filename = ""
for line in p.stdout:
    if linetype == 0:
       if i >= len(toprocess):
          break
       filename = toprocess[i]
       output_filename = os.path.join(options.output_dir, filename + ".features")
       f = open(output_filename, "w")
       f.write(line)
       linetype = 1
       i += 1
    else:
       f.write(line)
       f.close()
       linetype = 0
